<template>
  <div class="container my-4">
    <div class="card shadow-sm rounded-3 mx-auto" style="max-width: 800px;">
      <!-- Header -->
      <div class="card-header d-flex justify-content-between align-items-center">
        <h6 class="mb-0 fw-bold">用户列表</h6>
        <button class="btn btn-sm btn-primary rounded-pill" @click="openAdd">
          <i class="bi bi-person-plus"></i> 添加用户
        </button>
      </div>

      <!-- Table -->
      <div class="card-body p-0">
        <table class="table table-hover align-middle mb-0">
          <thead class="table-light">
            <tr class="text-center align-middle">
              <th>ID</th>
              <th>用户名</th>
              <th>角色</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in userStore.list" :key="user.id">
              <td class="text-center align-middle">{{ user.id }}</td>
              <td class="text-center align-middle">{{ user.username }}</td>
              <td class="text-center align-middle">
                <span class="badge bg-info text-dark" v-if="user.role==='admin'">管理员</span>
                <span class="badge bg-secondary" v-else>普通用户</span>
              </td>
              <td class="text-center align-middle">
                <button class="btn btn-sm btn-warning me-1 rounded-pill" @click="openEdit(user)">
                  <i class="bi bi-pencil-fill"></i> 编辑
                </button>
                <button class="btn btn-sm btn-danger rounded-pill" @click="removeUserConfirm(user)">
                  <i class="bi bi-trash-fill"></i> 删除
                </button>
              </td>
            </tr>

            <tr v-if="userStore.list.length === 0">
              <td colspan="4" class="text-center py-3">暂无用户</td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- Add/Edit Modal -->
      <div class="modal fade" ref="modalRef" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
          <div class="modal-content rounded-4 shadow">
            <div class="modal-header">
              <h5 class="modal-title">{{ editingUser ? '编辑用户' : '添加用户' }}</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
            </div>
            <div class="modal-body">
              <div class="mb-3">
                <label class="form-label">用户名</label>
                <input v-model="form.username" type="text" class="form-control" placeholder="请输入用户名">
              </div>

              <div class="mb-3">
                <label class="form-label">密码</label>
                <input
                  v-model="form.password"
                  type="password"
                  class="form-control"
                  placeholder="请输入密码"
                  :required="!editingUser"
                >
                <div class="form-text" v-if="editingUser">留空则不修改密码</div>
              </div>

              <div class="mb-3">
                <label class="form-label">角色</label>
                <select v-model="form.role" class="form-select">
                  <option value="admin">管理员</option>
                  <option value="user">普通用户</option>
                </select>
              </div>
            </div>
            <div class="modal-footer">
              <button class="btn btn-secondary rounded-pill" data-bs-dismiss="modal">取消</button>
              <button class="btn btn-primary rounded-pill" @click="saveUser">
                {{ editingUser ? '保存修改' : '添加' }}
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Delete Confirm Modal -->
      <div class="modal fade" ref="deleteModalRef" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
          <div class="modal-content rounded-4 shadow">
            <div class="modal-header">
              <h5 class="modal-title text-danger">
                <i class="bi bi-exclamation-triangle-fill me-2"></i>确认删除
              </h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
              确认要删除用户 <b>{{ deletingUser?.username }}</b> 吗？此操作不可撤销。
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary rounded-pill" data-bs-dismiss="modal">取消</button>
              <button type="button" class="btn btn-danger rounded-pill" @click="confirmDelete">确认删除</button>
            </div>
          </div>
        </div>
      </div>

    </div>

    <!-- Toast 组件（项目里应有） -->
    <Toast />
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { Modal } from 'bootstrap'
import { useUserStore } from '@/store/user'
import { useToastStore } from '@/store/toast'
import Toast from './Toast.vue'

const userStore = useUserStore()
const toastStore = useToastStore()

const modalRef = ref(null)
let modalInstance = null
const deleteModalRef = ref(null)
let deleteModalInstance = null

const editingUser = ref(null)
const form = ref({ username: '', password: '', role: 'user' })

const deletingUser = ref(null)

onMounted(async () => {
  await userStore.fetchUserList()
  // 等 DOM 渲染完成再初始化 modal，避免 ref 为空
  await nextTick()
  if (modalRef.value) modalInstance = new Modal(modalRef.value)
  if (deleteModalRef.value) deleteModalInstance = new Modal(deleteModalRef.value)
})

function openAdd() {
  editingUser.value = null
  form.value = { username: '', password: '', role: 'user' }
  if (!modalInstance && modalRef.value) modalInstance = new Modal(modalRef.value)
  modalInstance?.show()
}

function openEdit(user) {
  editingUser.value = user
  form.value = { username: user.username, password: '', role: user.role }
  if (!modalInstance && modalRef.value) modalInstance = new Modal(modalRef.value)
  modalInstance?.show()
}

async function saveUser() {
  if (!form.value.username.trim()) {
    toastStore.showToast('请输入用户名', 'warning')
    return
  }
  if (!editingUser.value && !form.value.password.trim()) {
    toastStore.showToast('请输入密码', 'warning')
    return
  }

  try {
    if (editingUser.value) {
      await userStore.updateUser(editingUser.value.id, {
        username: form.value.username,
        role: form.value.role,
        // 如果密码为空则不传密码字段（后端决定是否更新）
        ...(form.value.password ? { password: form.value.password } : {})
      })
      toastStore.showToast('用户更新成功', 'success')
    } else {
      await userStore.addUser(form.value)
      toastStore.showToast('用户添加成功', 'success')
    }
    modalInstance?.hide()
  } catch (err) {
    console.error(err)
    toastStore.showToast('操作失败', 'danger')
  }
}

function removeUserConfirm(user) {
  deletingUser.value = user
  if (!deleteModalInstance && deleteModalRef.value) deleteModalInstance = new Modal(deleteModalRef.value)
  deleteModalInstance?.show()
}

async function confirmDelete() {
  if (!deletingUser.value) return
  const u = deletingUser.value
  deleteModalInstance?.hide()
  deletingUser.value = null
  try {
    await userStore.deleteUserById(u.id)
    toastStore.showToast('用户删除成功', 'success')
  } catch (err) {
    console.error(err)
    toastStore.showToast('删除失败', 'danger')
  }
}
</script>
